﻿using System;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Confcloud.Email;
using Smarly.Bussines.Email;
using Smarly.Core;
using Smarly.Web.App_Start;
using Smarly.Web.ModelBinder;
using Smarly.Web.Storage;
using Smarly.Web.ViewEngine;
using log4net;

namespace Smarly.Web
{
	public class MvcApplication : System.Web.HttpApplication
	{
		protected void Application_Start()
		{
#if !DEBUG
			log4net.Config.XmlConfigurator.Configure();
#endif

			AreaRegistration.RegisterAllAreas();
			FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
			RouteConfig.RegisterRoutes(RouteTable.Routes);
			BundleConfig.RegisterBundles(BundleTable.Bundles);
			AuthConfig.RegisterAuth();

			ViewEngines.Engines.Clear();
			ViewEngines.Engines.Add(new SmarlyViewEngine());

			ModelBinders.Binders.DefaultBinder = new SmarlyModelBinder();


#if !DEBUG
			SubscriberSender.Start();
			EmailSender.SetTimerDate(DateTime.Now);

			Rss.Init();
			Sitemap.Init();
#endif

		}

#if !DEBUG
		private static readonly ILog log = LogManager.GetLogger("Smarly");
#endif

		protected void Application_Error(object sender, EventArgs e)
		{
			// excpt is the exception thrown
			// The exception that really happened is retrieved through the GetBaseException() method
			// because the exception returned by the GetLastError() is a HttpException
			Exception excpt = Server.GetLastError().GetBaseException();

#if !DEBUG

			string userName = string.Empty;
			if (User != null && User.Identity.IsAuthenticated)
				userName = ", Пользователь " + User.Identity.Name;

			log.Fatal("Необработанное исключение при запросе " + Request.Url.PathAndQuery + userName, new AspNetException(excpt)
				                                                                                          {
					                                                                                          Server = Server,
																																																		Request = Request,
																																																		User = User
				                                                                                          });
#endif

		}
	}
}